#当我想检测绳子的时候，我发现yolo的方法可能不太行，所以想尝试一下其他方法进行增强
#差分是其中一种

import argparse
import cv2
import numpy as np

def Parse_Arguments():
    parser = argparse.ArgumentParser(description="图片差分")
    parser.add_argument("--background-img", type=str, default=r"C:\Users\luoluoluo\Desktop\background\1.jpg")
    parser.add_argument("--source-img", type=str, default=r"C:\Users\luoluoluo\Desktop\elevator\999_97.jpg")
    return parser.parse_args()


def main():
    args = Parse_Arguments()
    background_img = args.background_img
    source_img = args.source_img

    image = cv2.imread(source_img)
    edges = cv2.Canny(image, 50, 150)
    # print(edges.shape)
    ref_image = cv2.imread(background_img)

    new_image = cv2.imread(source_img)
    diff_image = cv2.absdiff(ref_image, new_image)
    diff_image = cv2.cvtColor(diff_image, cv2.COLOR_BGR2GRAY)
    # _, thresh_image = cv2.threshold(diff_image, 50, 255, cv2.THRESH_BINARY)
    # # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 3))
    # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 3))
    # # kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
    # opened_image = cv2.morphologyEx(thresh_image, cv2.MORPH_OPEN, kernel)
    # # # 使用交叉形结构元素
    # # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 3))

    # # # 形态学操作：腐蚀和膨胀
    # # eroded = cv2.erode(thresh_image, kernel, iterations=1)
    # # dilated = cv2.dilate(eroded, kernel, iterations=1)

    # # contours, _ = cv2.findContours(opened_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # # for contour in contours:
    # #     if cv2.contourArea(contour) > 500:  # 这里500是一个阈值，可以根据需要调整
    # #         x, y, w, h = cv2.boundingRect(contour)
    # #         cv2.rectangle(new_image, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # # 使用Canny边缘检测
    # edges = cv2.Canny(opened_image, 50, 150)

    # # 使用霍夫变换检测线段
    # lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50, minLineLength=50, maxLineGap=10)

    # for line in lines:
    #     x1, y1, x2, y2 = line[0]
    #     cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    # print(type(diff_image))
    cv2.namedWindow("Detected Objects", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Detected Objects", 2240, 1260)
    cv2.imshow('Detected Objects', edges)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
if __name__ == "__main__":
    main()
